﻿using Autofac;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Web;
using WLYT.Common;
using WLYT.Domain.ApiModel;

namespace WLYT.Admin.WebApi.Component
{
    public class WebApiInvoke
    {
        /// <summary>
        /// 调用API接口，通过反射调用API接口业务逻辑层方法
        /// </summary>
        /// <param name="apiParam">Api参数实体信息</param> 
        /// <returns></returns>
        public ApiResult Invoke(ApiParam apiParam)
        {
            try
            {
                string url = $"http://{HttpContext.Current.Request.Url.Authority}/api/{apiParam.ApiName.Replace('.', '/')}";
                return JsonConvert.DeserializeObject<ApiResult>(WebUtils.HttpPost(url, apiParam.ParamData));

                //if (!apiParam.ApiName.StartsWith("WLYT.Admin.WebApi.Controllers."))
                //    apiParam.ApiName = "WLYT.Admin.WebApi.Controllers." + apiParam.ApiName;

                ////获取接口的方法名称
                //string methodName = apiParam.ApiName.Substring(apiParam.ApiName.LastIndexOf(".") + 1);
                ////获取接口方法的类型名称
                //string typeName = apiParam.ApiName.Substring(0, apiParam.ApiName.LastIndexOf(".")) + "Controller";

                //Assembly assembly = Assembly.GetExecutingAssembly(); // 获取当前程序集 
                ////object obj = assembly.CreateInstance(typeName);

                //Type type = assembly.GetType(typeName);
                //object obj = GetInstance(type);

                //MethodInfo method = type.GetMethod(methodName, new Type[] { typeof(string) });
                //object[] objParams = new object[] { apiParam.ParamData == null ? "" : apiParam.ParamData.ToString() };
                //var result = (Task<ApiResult>)method.Invoke(obj, objParams);
                //return result;
            }
            catch (Exception ex)
            {
                Exception inEx = ex.InnerException;
                throw new Exception(inEx.Message);
            }
        }

        public object GetInstance(Type type)
        {
            List<object> param = new List<object>();
            //获取第一个构造函数的参数
            var parameters = type.GetConstructors()[0].GetParameters();
            foreach (var item in parameters)
            {
                param.Add(AutofacConfig._container.Resolve(item.ParameterType));
            }
            return Activator.CreateInstance(type, param.ToArray());
        }


    }

}